// stores/useChat.js 聊天记录相关
import { defineStore } from "pinia";
import { ref, computed } from "vue";

const useChat = defineStore("useChat", () => {
  // 当前用户
  const user = ref({
    nickname: "coffce",
    img: "https://img2.baidu.com/it/u=1310029438,409566289&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1732294800&t=7fb44f96d1ad0c507e44638810a32801",
  });
  const currentPlayId = ref("");
  // 会话列表
  const sessions = ref(uni.getStorageSync("vue-chat-session") || []);
  // 当前选中的会话
  const currentSessionId = ref("");
  // 过滤出只包含这个key的会话
  const filterKey = ref("");
  //记录是否正在等待智能体回复 对讲模式用
  const waitReplay = ref(false);
  //流式的用户asr的文字
  const userInputText = ref("");
  //流式的智能体回复的tts的文字
  const clientReplayText = ref("");
  //获取当前会话的聊天对象信息以及聊天记录
  const session = computed(
    () =>
      sessions.value.find(
        (session) => session.groupId === currentSessionId.value
      ) || []
  );

  /**
   * 流式显示文字userInputText/clientReplayText,实现页面打字机效果
   * @param {*} key userInputText/clientReplayText 输入/输出
   * @param {*} str 塞入的文字
   * @param {*} isEnd 当前输入是否已经塞入结束
   */
  function serStreamText(key, str, isEnd) {
    [key].value = str;
    //如果本次是输入+文字 则需要设置等待智能体回复状态
    if (key == "userInputText" && isEnd) {
      waitReplay.value = true;
    }
  }

  //设置是否正在等待智能体回复
  function setWaitStatus(f) {
    waitReplay.value = f;
  }
  //缓存消息
  function setMessage(messages) {
    messages.length &&
      sessions.value.map((item, index) => {
        if (item.groupId == messages[0].groupId) {
          sessions.value[index].messages = [...messages];
        }
        return item;
      });
    uni.setStorageSync("vue-chat-session", JSON.stringify(sessions.value));
  }
  //初始化对话消息列表 ------ 智能体列表
  function initChatData(list) {
    let data = uni.getStorageSync("vue-chat-session");
    if (data) {
      sessions.value = JSON.parse(data);
      list?.map((item) => {
        sessions.value.map((s, index) => {
          if (item.groupId == s.groupId) {
            let messages = s.messages;
            sessions.value[index] = {
              ...{ agentId: s.agentId, groupId: s.groupId },
              ...{ messages: messages },
            };
          }
        });
      });
    } else {
      if (list && list?.length) {
        let arr = [];
        list.map((n) => {
          arr.push({
            agentId: n.agentId,
            groupId: n.groupId,
            messages: [],
          });
        });

        sessions.value = arr;
        // sessions.value.map((item) => {
        //   item.messages = [];
        // });
      }
      uni.setStorageSync("vue-chat-session", JSON.stringify(sessions.value));
    }
  }

  //判断是否第一次对话 是第一次初始化本地缓存消息列表为空
  function checkNewUserChat(data) {
    let isHave = sessions.value.some((item) => {
      return item.groupId == data.groupId;
    });
    if (!isHave) {
      sessions.value.push({ ...data, ...{ messages: [] } });
    }
  }
  // 发送消息
  function sendMessage(data, cb) {
    let session = sessions.value.find(
      (item) => item.groupId === this.currentSessionId
    );
    session.messages &&
      session.messages.push({
        content: data.content,
        type: data.type,
        date: new Date().getTime(),
        roleType: data.roleType,
        messageType: data.messageType || "1", //1:文本 2:图片 3:视频 4:音频 5:文件 6:链接
        tempId: data.tempId || null,
      });
    //本地最多缓存100条数据
    if (session.messages.length > 100) {
      let len = session.messages.length;
      session.messages = session.messages.splice(len - 100, len);
    }
    cb && cb();
    uni.setStorageSync("vue-chat-session", JSON.stringify(sessions.value));
  }

  //更新聊天记录的流式消息
  function setStreamMessageByTempId(tempId, content) {
    let session = sessions.value.find(
      (item) => item.groupId === this.currentSessionId
    );
    session.messages &&
      session.messages.map((item) => {
        if (item.tempId == tempId) {
          item.content = content;
        }
      });
    uni.setStorageSync("vue-chat-session", JSON.stringify(sessions.value));
  }

  //选择会话
  function selectSession(groupId) {
    currentSessionId.value = groupId;
  }

  //清除上下文 => 清除聊天记录，替换groupId
  function clearMsgAndGroupId(newGroupId) {
    sessions.value.map((item, index) => {
      if (item.groupId == currentSessionId.value) {
        sessions.value[index].messages = [];
        sessions.value[index].groupId = newGroupId;
      }
    });

    //重新赋值当前groupId
    currentSessionId.value = newGroupId;

    uni.setStorageSync("vue-chat-session", JSON.stringify(sessions.value));
  }
  return {
    user,
    sessions,
    currentSessionId,
    filterKey,
    waitReplay,
    userInputText,
    clientReplayText,
    currentPlayId,
    serStreamText,
    setWaitStatus,
    setMessage,
    initChatData,
    checkNewUserChat,
    sendMessage,
    setStreamMessageByTempId,
    selectSession,
    clearMsgAndGroupId,

    session,
  };
});

export default useChat;
